package cn.longwingstech.intelligence.agent.aop;

import cn.dev33.satoken.stp.StpUtil;
import cn.longwingstech.intelligence.agent.monitor.AiModelMetricsCollector;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;

/**
 * 统计API请求次数
 */
//@Aspect
//@Component
public class ApiRequestCountAspect {
    @Resource
    private AiModelMetricsCollector aiModelMonitorListener;
    // 监听cn.longwingstech.intelligence.agent.contoller 下的所有方法
    @Around("execution(* cn.longwingstech.intelligence.agent.controller..*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        // 获取方法名称
        String name = method.getName();
        aiModelMonitorListener.recordRequest(name);
        Instant start = Instant.now();
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            return proceed;
        } finally {
            Instant end = Instant.now();
            Duration duration = Duration.between(start, end);
            aiModelMonitorListener.recordRequestResponseTime(name, duration);
        }

    }
}
